<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="学生姓名" prop="studentName">
        <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-input v-model="queryParams.grade" placeholder="请输入年级" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-input v-model="queryParams.className" placeholder="请输入班级" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="入学日期" prop="enrollDate">
        <el-date-picker clearable v-model="queryParams.enrollDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择入学日期" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['eduManage:student:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['eduManage:student:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['eduManage:student:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['eduManage:student:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload :headers="headers" :action="importUrl" :on-success="handleImportSuccess" :show-file-list="false" accept=".xlsx, .xls">
          <el-button type="primary" plain icon="el-icon-upload" size="mini" v-hasPermi="['eduManage:student:import']">导入</el-button>
        </el-upload>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="年级" align="center" prop="grade" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="入学日期" align="center" prop="enrollDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.enrollDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="积分数" align="center" prop="points" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['eduManage:student:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['eduManage:student:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleViewPointsLog(scope.row)" v-hasPermi="['manage:student:query']">积分记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入年级" />
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="入学日期" prop="enrollDate">
          <el-date-picker clearable v-model="form.enrollDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择入学日期" />
        </el-form-item>
        <el-form-item label="积分数" prop="points">
          <el-input-number v-model="form.points" :min="0" :max="999999" :step="1" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="逻辑删除标识" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入逻辑删除标识" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 积分变更记录弹窗 -->
    <el-dialog :title="pointsLogTitle" :visible.sync="pointsLogOpen" width="700px" append-to-body>
      <el-table v-loading="pointsLogLoading" :data="pointsLogList">
        <el-table-column label="时间" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="变更前" prop="beforePoints" />
        <el-table-column label="变更值" prop="changeAmount" />
        <el-table-column label="变更后" prop="afterPoints" />
        <el-table-column label="原因" prop="reason" />
        <el-table-column label="操作人" prop="operator" />
        <el-table-column label="备注" prop="remark" />
      </el-table>
      <pagination v-show="pointsLogTotal > 0" :total="pointsLogTotal" :page.sync="pointsLogQuery.pageNum" :limit.sync="pointsLogQuery.pageSize" @pagination="getPointsLogList" />
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent, exportStudent } from "@/api/manage/student";
import { getToken } from "@/utils/auth";
import { listStudentPointsLog } from "@/api/manage/pointsLog";

export default {
  name: "Student",
  dicts: ['sys_user_sex', 'sys_normal_disable'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      studentList: [],
      title: "",
      open: false,
      // 积分记录弹窗与数据
      pointsLogOpen: false,
      pointsLogTitle: "积分变更记录",
      pointsLogLoading: false,
      pointsLogList: [],
      pointsLogTotal: 0,
      pointsLogQuery: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        grade: null,
        className: null,
        phone: null,
        gender: null,
        enrollDate: null,
        status: null,
      },
      form: {},
      rules: {
        studentName: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/ , message: "请输入正确手机号", trigger: "blur" }
        ]
      },
      headers: { Authorization: "Bearer " + getToken() },
      importUrl: process.env.VUE_APP_BASE_API + "/eduManage/student/importData"
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生信息列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        studentId: null,
        studentName: null,
        grade: null,
        className: null,
        phone: null,
        gender: null,
        enrollDate: null,
        points: 0,
        status: null,
        remark: null,
        delFlag: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.studentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const studentId = row.studentId || this.ids
      getStudent(studentId).then(response => {
        this.form = response.data;
        // 确保积分数在编辑时有默认值
        if (this.form.points === null || this.form.points === undefined) {
          this.form.points = 0;
        }
        this.open = true;
        this.title = "修改学生信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.studentId != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const studentIds = row.studentId || this.ids;
      this.$modal.confirm('是否确认删除学生信息编号为"' + studentIds + '"的数据项？').then(function() {
        return delStudent(studentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('eduManage/student/export', {
        ...this.queryParams
      }, `student_${new Date().getTime()}.xlsx`)
    },
    /** 查看积分记录 */
    handleViewPointsLog(row) {
      this.pointsLogQuery.studentId = row.studentId;
      this.pointsLogQuery.pageNum = 1;
      this.pointsLogOpen = true;
      this.getPointsLogList();
    },
    /** 获取积分记录列表 */
    getPointsLogList() {
      this.pointsLogLoading = true;
      listStudentPointsLog(this.pointsLogQuery).then(response => {
        this.pointsLogList = response.rows || [];
        this.pointsLogTotal = response.total || 0;
        this.pointsLogLoading = false;
      }).catch(() => {
        this.pointsLogLoading = false;
      });
    },
    /** 导入成功回调 */
    handleImportSuccess(response) {
      if (response.code === 200) {
        this.$modal.msgSuccess('导入成功');
        this.getList();
      } else {
        this.$modal.msgError(response.msg || '导入失败');
      }
    }
  }
}
</script>

<style scoped>
</style>